package p2pEngine;

import java.io.*;
import java.net.*;
import player.*;
import netPacks.*;

public class p2pCon extends Thread{

	int DEFAULT_GAME_PORT = 7000;
	int gamePort = DEFAULT_GAME_PORT;
	Socket gameSocket = null;
    ServerSocket hostSocket = null;
    public ObjectInputStream gameOis = null;
    public ObjectOutputStream gameOos = null;
    message tmp = new message();
    pinger pingyClient = null;
	
	private static volatile p2pCon instance = null;
    
    public static p2pCon getInstance() {
        if (instance == null){
            synchronized (p2pCon.class){
                    if (instance == null){
                        instance = new p2pCon();
                    }
        }}
        return instance;
    }
    
    public void run(){
    	if(player.getInstance().getIsHost()){
    		try {
				this.hostSocket = new ServerSocket(this.gamePort);
    			this.gameSocket = this.hostSocket.accept();
            	this.gameOos = new ObjectOutputStream(gameSocket.getOutputStream());
            	this.gameOos.flush();
            	this.gameOis = new ObjectInputStream(gameSocket.getInputStream());
			} 
    		catch (IOException e) {
				System.err.println("Cannot open game listening socket. \n"+e.getMessage());
			}
    		
    	}
    	else if(!player.getInstance().getIsHost()){
    		try {
				this.gameSocket = new Socket(player.getInstance().getOpIp(), this.gamePort);
            	this.gameOos = new ObjectOutputStream(gameSocket.getOutputStream());
            	this.gameOos.flush();
            	this.gameOis = new ObjectInputStream(gameSocket.getInputStream());
			} 
    		catch (IOException e) {
				System.err.println("Cannot open game socket/IO streams. \n"+e.getMessage());
			}
    	}
		while(true){
			try {
				this.tmp = (message) this.gameOis.readObject();
			}
			catch(IOException e1){
				this.closeP2PConnection();
				System.err.println("I/O exception in gameOis. Closing connection.\n"+e1.getMessage());
				e1.printStackTrace();
			}
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
        	msgHandler.getInstance().msgQ.add(tmp);
    	}
    }
    
	public void closeP2PConnection(){
		if(this.gameSocket != null){
			try{
				this.gameOis.close();
				this.gameOos.close();
				this.gameSocket.close();
				if(this.hostSocket != null){
					this.hostSocket.close();
				}
		}
        catch(IOException e){
            System.err.println("cannot close the p2p connection. \n"+e.getMessage());
        }
		this.gameSocket = null;
		this.hostSocket = null;
		this.gameOis = null;
		this.gameOos = null;
		p2pCon.instance = null;
	}
	}
    
}
